<template>
  <div>
    <h3 class="forget-title">修改/找回密码</h3>
    <el-steps :active="active" align-center finish-status="success">
      <el-step title="验证手机"></el-step>
      <el-step title="填写密码"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <hr />

    <div v-show="active === 0" class="forget-from">
      <el-form :model="codeForm" :rules="codeRules" ref="codeForm" label-width="100px">
        <el-form-item>
          <span class="text-muted" v-if="!isLogin">请填写手机号码，并填写您收到的验证码</span>
          <span class="text-muted" v-else>请点击“获取验证码”按钮，并填写您收到的验证码</span>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="codeForm.phone" placeholder="手机号码" :disabled="isLogin"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="codeForm.code" placeholder="验证码" @keyup.enter.native="checkCode">
            <el-button
              slot="append"
              @click="getCode"
              :disabled="codeBtnDisabled"
              :loading="codeBtnLoading"
            >
              {{ codeBtnText }}
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkCode">下一步</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-show="active === 1" class="forget-from">
      <el-form :model="pwd" :rules="pwdRules" ref="pwdForm" label-width="100px">
        <el-form-item>
          <span class="text-muted">请填写您的新密码</span>
        </el-form-item>
        <el-form-item label="新密码" prop="new1">
          <el-input type="password" v-model="pwd.new1" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="再次输入" prop="new2">
          <el-input type="password" v-model="pwd.new2" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="changePwd">下一步</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-show="active === 2" class="forget-from text-center" style="padding: 30px 0">
      <p><i class="fa fa-check-circle fa-4x text-success"></i></p>
      <p>密码修改成功！下次请用新密码登录。</p>
      <hr />
      <router-link to="/login" class="btn btn-success">去登录</router-link>
    </div>
  </div>
</template>

<script>
import { cookieWrite, cookieGet } from '@vimi/utils-tool'
import { pwdMd5 } from '@/common/api/auth'
import { checkMobile } from '@/common/plugins/validator'
export default {
  components: {},

  props: {},

  data() {
    let validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else if (!checkMobile(value)) {
        callback(new Error('手机号码有误，请重新输入'))
      } else {
        callback()
      }
    }
    let validatePwdConfirm = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pwd.new1) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      active: 0,

      // 手机验证
      isLogin: false,
      codeForm: {
        phone: '',
        code: '',
      },
      codeRules: {
        phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
      codeBtnDisabled: false,
      codeBtnLoading: false,
      codeCountTime: 60,
      codeBtnText: '获取验证码',

      // 密码
      pwd: {
        new1: '',
        new2: '',
      },
      pwdRules: {
        new1: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        new2: [{ required: true, validator: validatePwdConfirm, trigger: 'blur' }],
      },
    }
  },

  computed: {},

  watch: {},

  created() {},

  mounted() {
    this.initPhone()
    this.initCode()
  },

  methods: {
    // 判断是否登录，如果登录，自动获取手机号码
    initPhone() {
      let me = this.$store.getters.userData
      if (me) {
        this.codeForm.phone = me.phoneNumber
        this.isLogin = true
      } else {
        let cookie = cookieGet('vimiauth')
        if (cookie) {
          this.getMe()
        } else {
          this.isLogin = false
        }
      }
    },

    // 当 cookie 存在并 $store 中无个人信息，从服务器中获取个人信息
    async getMe() {
      try {
        let res = await this.$http.get('/auth/user/me/')
        this.isLogin = true
        this.$store.commit('userData', res.data)
        this.codeForm.phone = res.data.phoneNumber
      } catch (e) {
        this.isLogin = false
      }
    },

    // 验证验证码是否正确
    checkCode() {
      this.$refs.codeForm.validate(async valid => {
        if (valid) {
          this.getCheckCode()
        } else {
          this.$message.error('输入错误，请重新输入')
        }
      })
    },

    // 请求服务器验证码是否正确
    getCheckCode() {
      this.$http
        .get(`/auth/user/checkCode/?verifyCode=${this.codeForm.phone + this.codeForm.code}`)
        .then(res => {
          if (res.data > 0) {
            this.active++
          } else {
            this.$message.error('验证码错误，请重新错误！')
          }
        })
        .catch(() => {
          this.$message.error('验证码错误，请重新错误！')
        })
    },

    // 获取验证码
    getCode() {
      this.$refs.codeForm.validateField('phone', async msg => {
        if (msg) {
          return
        }

        try {
          this.codeBtnLoading = true
          await this.$http.post(`/auth/user/reset/codes/?phoneNumber=${this.codeForm.phone}`)
          this.$message.success('验证码获取成功，请稍后查看您的手机短信！')

          let time = new Date().getTime() + this.codeCountTime * 1000
          cookieWrite('verifycode', time, this.codeCountTime * 1000)

          this.initInterval(this.codeCountTime)
        } catch (e) {
          if (e && e.status === 400 && e.data.error === 'operate_too_fast') {
            this.$message.error('操作太频繁，请隔60s后再获取！')
          } else {
            this.$message.error('获取验证码失败，请重新获取！(' + e.status + ')')
          }
        } finally {
          this.codeBtnLoading = false
        }
      })
    },

    // 设置验证码倒计时
    initInterval(time) {
      let resend = setInterval(() => {
        time--
        if (time > 0) {
          this.codeBtnText = time + '秒后重新获取'
          this.codeBtnDisabled = true
        } else {
          clearInterval(resend)
          this.codeBtnText = '获取验证码'
          this.codeBtnDisabled = false
        }
      }, 1000)
    },

    // 初始化验证码
    initCode() {
      let verifyCookie = cookieGet('verifycode') || 0
      let time = Math.ceil((+verifyCookie - new Date().getTime()) / 1000)
      if (time > 0) {
        this.initInterval(time)
      } else {
        this.codeBtnDisabled = false
      }
    },

    // 更改密码
    changePwd() {
      this.$refs.pwdForm.validate(valid => {
        if (valid) {
          this.postPassword()
        } else {
          this.$message.error('输入错误，请重新输入！')
        }
      })
    },

    // 请求服务器更改密码
    async postPassword() {
      try {
        var params = {
          newPassword: pwdMd5(this.pwd.new1),
          phoneNumber: this.codeForm.phone,
          verifyCode: this.codeForm.code,
        }
        let res = await this.$http.put('/auth/user/reset/password/', params)
        if (res.data > 0) {
          this.active++
        } else {
          this.$message.error('修改密码失败，请重新修改！')
        }
      } catch (e) {
        if (e && e.data) {
          if (
            e.status === 500 &&
            e.data.error === 'invalid_param' &&
            e.data.errorDescription === 'verify code timeout'
          ) {
            this.$message.error('验证码已过期，请重新获取验证码！')
          } else if (
            e.status === 400 &&
            e.data.error === 'check_code' &&
            e.data.errorDescription === 'verify code is not right'
          ) {
            this.$message.error('验证码错误，请重填写验证码！')
          } else {
            this.$message.error('修改密码失败，请重新修改！')
          }
          this.codeForm.code = ''
          this.pwd.new1 = ''
          this.pwd.new2 = ''
          this.active = 0
        } else {
          this.$message.error('修改密码失败，请重新修改！')
        }
      }
    },
  },
}
</script>

<style scoped>
.forget-title {
  margin: 10px 20px 30px 20px;
  font-size: 16px;
  font-weight: bold;
  color: #666;
}

.forget-from {
  max-width: 500px;
  margin: 0 auto;
}
</style>
